<?php

namespace App\Http\Controllers\Api\V6;

use App\Common\ApiData;
use App\Models\V1\CloMemberInfo;
use App\Models\V1\Comment;
use App\Models\V1\LearningOfficerMatter;
use App\Models\V1\Lessons;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UsersChangeController extends BaseController
{
    /**
     * @var ApiData
     */
    private $apiData;

    public function __construct(ApiData $apiData)
    {

        $this->apiData = $apiData;
    }

    /**
     * 修改用户评论的点赞次数
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @internal param $type 1为学习官课堂的评论 2为学习官那点事的评论
     * @internal param 评论的ID $comment_id
     */
    public function change_up_times(Request $request)
    {
        $type       = $request->type;
        $comment_id = $request->comment_id;
        $user_phone = $request->userPhone;
        if ($type && $comment_id && $user_phone) {
            $comment_data = Comment::where('type', $type)->where('id', $comment_id)->pluck('up_time_user')->first();
            $data         = explode(',', $comment_data);
            if ($key = array_search($user_phone, $data)) {
                $comment_status = DB::table('comments')
                    ->where('type', $type)
                    ->where('id', $comment_id)
                    ->decrement('up_times');
                unset($data[$key]);
                $data = implode(',', $data);
                Comment::where('type', $type)->where('id', $comment_id)->update([
                    'up_time_user' => $data
                ]);
                return $this->apiData->set_data('deleteUpTimes', '取消点赞成功')->send(201, '取消点赞成功');
            }
            array_push($data, $user_phone);
            $data = implode(',', $data);
            Comment::where('type', $type)->where('id', $comment_id)->update([
                'up_time_user' => $data
            ]);
            $comment_status = DB::table('comments')
                ->where('type', $type)
                ->where('id', $comment_id)
                ->increment('up_times');
            if ($comment_status) {
                return $this->apiData->send(200, '点赞成功');
            }
        }
        return $this->apiData->send(404, '点赞失败');
    }

    /**
     * @param $clo_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function change_flower_clo(Request $request)
    {
        $clo_id     = $request->cloId;
        $user_phone = $request->userPhone;

        if ($clo_id && $user_phone) {
            $flower_user = CloMemberInfo::where('clo_id', $clo_id)->pluck('flower_user')->first();

            $data = explode(',', $flower_user);

            if ($key = array_search($user_phone, $data)) {//如果用户已经送过花了

                DB::table('my_clo_member_user_info')
                    ->where('clo_id', $clo_id)
                    ->decrement('flower');
                unset($data[$key]);
                $data = implode(',', $data);
                CloMemberInfo::where('clo_id', $clo_id)->update([
                    'flower_user' => $data
                ]);
                return $this->apiData->set_data('flower', '取消送花成功')->send(200, '取消送花成功');
            }

            array_push($data, $user_phone);
            $data = implode(',', $data);
            CloMemberInfo::where('clo_id', $clo_id)->update([
                'flower_user' => $data
            ]);

            $flower_status = DB::table('my_clo_member_user_info')
                ->where('clo_id', $clo_id)
                ->increment('flower');
            if ($flower_status) {
                return $this->apiData->send(200, '送花成功');
            }
            return $this->apiData->send(404, '送花失败');
        }
        return $this->apiData->set_data('flowerError', '送花错误')->send(404, '参数错误');

    }

    /**
     * 文章点赞次数修改
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @internal param $articleId
     */
    public function change_article_uptimes(Request $request)
    {
        $articleId  = $request->articleId;
        $user_phone = $request->userPhone;
        if ($articleId && $user_phone) {
            $article_data = LearningOfficerMatter::where('id', $articleId)->pluck('article_up_times_user')->first();
            $data         = explode(',', $article_data);
            if ($key = array_search($user_phone, $data)) {
                DB::table('learning_officer_matter')->where('id', $articleId)->decrement('up_times');//修改点赞的次数
                unset($data[$key]);
                $data = implode(',', $data);
                LearningOfficerMatter::where('id', $articleId)->update([
                    'article_up_times_user' => $data
                ]);
                return $this->apiData->set_data('flower', '取消点赞成功')->send(200, '取消点赞成功');
            }
            array_push($data, $user_phone);
            $data = implode(',', $data);
            LearningOfficerMatter::where('id', $articleId)->update([
                'article_up_times_user' => $data
            ]);
            $article_up_times = DB::table('learning_officer_matter')->where('id', $articleId)->increment('up_times');
            if ($article_up_times) {
                return $this->apiData->send(200, '点赞成功');
            }
        }
        return $this->apiData->send(404, '点赞失败');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_comments(Request $request, Lessons $lessons)
    {
//        mylogger($request->all());
        $userId         = $request->userId;//当前用户的Id
        $pid            = $request->commentId;//评论的Id如果没有则commentId为0
        $replay_user_id = $request->replay_user_id;//当前用户回复用户的ID
        $body           = $request->body;//评论的内容
        $lessons_id     = $request->lessonsId;//用户评论的课程Id
        $type           = $request->type;//用户评论的类型 1为视频内容的评论，2为文章类型的评论

        $comment_pid = $request->commentTopId;//评论的顶级ID有前端提供

        $comment = Comment::create([
            'user_id'        => $userId,
            'pid'            => $pid,
            'replay_user_id' => $replay_user_id,
            'body'           => $body,
            'lessons_id'     => $lessons_id,
            'type'           => $type
        ]);

        if ($comment_pid) {//用户回复评论
            $data = $lessons->get_single_coment($comment_pid, $comment->user_id);//评论的顶级ID,当前用户的ID
            DB::table('learning_officer_matter')->where('id', $lessons_id)->increment('comment_times');
            return $this->apiData->set_data('comment', $data)->send(200, '添加回复成功');
        }

        //用户评论
        $commentAry     = $comment->toArray();
        $userInfo       = DB::table('comments as c')
            ->select('c.*', 'm.YourName', 'm.FilePath1', 'mm.YourName as replyName')
            ->where('c.id', '=', $commentAry['id'])
            ->join('memberinfo as m', 'm.UserID', '=', 'c.user_id')
            ->leftJoin('memberinfo as mm', 'mm.UserID', '=', 'c.replay_user_id')
            ->whereNull('c.deleted_at')
            ->orderBy('created_at', 'asc')
            ->first();
        $userInfo->body = emoji_text_decode($userInfo->body);
        $mobile         = DB::table('memberinfo')->where('UserID', $userInfo->user_id)->first();

        $mobile           = $mobile->UserName;
        $userInfo->isLike = preg_match("/$mobile/", $userInfo->up_time_user) ? 1 : 0;

        $userInfo->FilePath1 = change_member_head_img($userInfo->FilePath1);
        if ($userInfo->pid == 0) {
            $userInfo->sub_comments = [];
        }
        if ($userInfo) {
            //更新文章或者视频的评论的次数
            if ($type == 2) {
                DB::table('learning_officer_matter')->where('id', $lessons_id)->increment('comment_times');
            }
            return $this->apiData->set_data('comment', $userInfo)->send(200, '添加评论成功');
        }
        return $this->apiData->send(300, '添加评论失败');
    }

    //用户HTML页面
    public function share($id)
    {
        $data = LearningOfficerMatter::where('id', $id)->first()->toArray();
        $date = Carbon::parse($data['created_at'])->toDateString();
        return view('web.share.index', compact('data', 'date'));
    }

    //用户的分享的页面
    public function info($id, LearningOfficerMatter $learningOfficerMatter, $user_phone = 666)
    {
        //获取评论的信息
        $comments_detail = DB::table('comments as c')
            ->select('c.*', 'm.FilePath1', 'm.YourName', 'mm.YourName as replay_name', 'm.UserName as userPhone', 'c.up_time_user')
            ->where('c.lessons_id', $id)
            ->Join('memberinfo as m', 'c.user_id', '=', 'm.UserID')
            ->leftJoin('memberinfo as mm', 'c.replay_user_id', '=', 'mm.UserID')
            ->whereNull('c.deleted_at')
            ->where('type', 2)
            ->get()->toArray();
        $lessons         = new Lessons();
        //判断用户是否已经点过赞了

        foreach ($comments_detail as $key => $value) {
            $str           = substr($value->up_time_user, 1);
            $value->isLike = preg_match("/$user_phone/", $str) ? 1 : 0;
        }
        $comments_detail = $lessons->comments_data($comments_detail);

//        dd($comments_detail);
        //修改用户点击观看文章的时候观看的次数
        DB::table('learning_officer_matter')->where('id', $id)->increment('looking_times');

        $article_detail = LearningOfficerMatter::where('id', $id)->first()->toArray();
//        dd($article_detail);
        $article['comments']      = $comments_detail;
        $article['articleDetail'] = $article_detail;

        //获取所有的用户点赞人数
        $user_phones = explode(',', $article_detail['article_up_times_user']);
        unset($user_phones[0]);//去除空数据

        if (in_array($user_phone, $user_phones)) {//如果用户已经点赞了
            $article['isLike'] = 1; //1为点赞过
        } else {
            $article['isLike'] = 0;//0为没有点赞过
        }
        $shareData = [
            'title'     => $article_detail['title'],
            'share_img' => $article_detail['article_img'],
            'introduce' => $article_detail['introduce'],
            'link'      => url('/api/v4/share', ['id' => $id])
        ];
        $tmp       = [];
        array_push($article, $shareData);
        foreach ($article as $key => $value) {
            if ($key == 0) {
                $tmp = $value;
                unset($article[$key]);
            }
            $article['shareInfo'] = $tmp;
        }
        $comments = $article['comments'];

        $articleDetail = $article['articleDetail'];
        $isLike        = $article['isLike'];
        $shareInfo     = $article['shareInfo'];
        //dd($comments);
        $wxUserPhone = session('wxUserInfo')['UserName'];
        return view('web.share.wx', compact('comments', 'articleDetail', 'isLike', 'shareInfo', 'wxUserPhone'));
    }
}
